import requests, re
from bs4 import BeautifulSoup
from utils.log_util import logger
from .ServerUtils import server_utils, CaptchaError


class user_server_action:

    def get_user_info_id(self, mobilePhone):
        """
        发送请求获取用户信息并解析页面以提取用户 ID。
        """
        try:
            params = {"mobilePhone": mobilePhone}
            response = server_utils.get_request(url="/userInfo/list.html", params=params).text
            if response:
                soup = BeautifulSoup(response, 'html.parser')
                span_element = soup.find('span', id='m-switch-0')
                if span_element:
                    onclick_value = span_element.get('onclick', '')
                    match = re.search(r"permissions\(this,'([^']*)'", onclick_value)
                    if match:
                        return match.group(1)
            else:
                print("获取用户信息失败或响应无效。")
        except Exception as e:
            print(f"请求出现异常: {e}")

        return None

    def get_user_info_rsNo(self, mobilePhone):
        """
        发送请求获取用户信息并解析页面以提取用户 rsNo。
        """
        try:
            params = {"mobilePhone": mobilePhone}
            response = server_utils.get_request(url="/userInfo/list.html", params=params).text
            values = []
            if response:
                soup = BeautifulSoup(response, 'html.parser')
                # 查找所有的 onclick 属性值
                divs = soup.find_all('div', attrs={'class': 'item-btn-box'})
                if divs:
                    for div in divs:
                        onclick_value = div.get('onclick', '')
                        # 匹配 toaddorupdate 函数及其参数
                        match = re.search(r"toaddorupdate\('([^']*)'\s*,\s*'([^']*)'\)", onclick_value)
                        if match:
                            values.append(match.group(1))  # 添加第一个参数值
                            return values[0]
            else:
                print("获取用户信息失败或响应无效。")
        except Exception as e:
            print(f"请求出现异常: {e}")

        return None

    def reset_user_password(self, user_id):
        """
        重置用户密码。
        """
        if user_id:
            data = {"id": user_id}
            response = server_utils.post_request(url="/userInfo/resetPassword.html", data=data).json()
            if response:
                return response
            else:
                print("重置密码请求失败或响应无效。")
        else:
            print("无法重置密码，未找到有效的用户 ID。")

    def update_user_phone(self, rsno_value, username, mobile_phone):
        """
        修改用户手机号。
        """
        if rsno_value:
            data = {"rsNo": rsno_value, "userName": username, "mobilePhone": mobile_phone}
            response = server_utils.post_request(url="/userInfo/updateMobilePhone.html", data=data).json()
            if response:
                return response
            else:
                print("修改手机号请求失败或响应无效。")
        else:
            print("无法修改手机号，未找到有效的用户 ID。")

    @staticmethod
    def userSmsInfo(mobile_phone):
        """
        获取用户短信验证码
        """
        params = {"mobilePhone": mobile_phone}
        response = server_utils.get_request(url="/smsInfo/list.html", params=params).text
        # 创建 BeautifulSoup 对象
        soup = BeautifulSoup(response, 'html.parser')
        # print(soup)

        # 查找第一个包含 "您的验证码是:" 的 <td> 标签
        target_td = soup.find('td', text=re.compile(r'您的验证码是.*'))
        # print(target_td)

        # 提取验证码后面的数字
        if target_td:
            # 使用正则提取验证码数字
            verification_code = re.search(r'您的验证码是：\s*(\d+)', target_td.text)
            if verification_code:
                return verification_code.group(1)  # 返回验证码
            else:
                print("未找到验证码")
        else:
            print("未找到包含验证码的<td>标签")

    @staticmethod
    def addSmsWhiteList(mobile_phone):
        """
        添加短信白名单
        """
        try:
            data = {"id": "", "mobilePhone": mobile_phone, "_validator_ajaxsubmit": True}
            response = server_utils.post_request(url="/smsWhiteList/addorupdate.html", data=data).json()
            return response
        except Exception as e:
            raise CaptchaError(f"后台添加短信白名单失败{mobile_phone}: {e}") from e


user_server = user_server_action()
